package com.demo.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.demo.mapper.UserMapper;
import com.demo.pojo.User;
import com.demo.pojo.UserExcel;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;


@Slf4j
public class ExcelBatchImportListener extends AnalysisEventListener<UserExcel> {


    private List<UserExcel> list;

    private StringBuilder stringBuilder;

    private UserMapper userMapper;

    private static final String FORMAT_R_N = System.getProperty("line.separator");



    public ExcelBatchImportListener(List<UserExcel> list, StringBuilder stringBuilder, UserMapper userMapper) {
        this.list = list;
        this.stringBuilder = stringBuilder;
        this.userMapper = userMapper;
    }

    @Override
    public void invoke(UserExcel data, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", data.toString());
        list.add(data);
    }




    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("所有数据解析完成！");
        if (!CollectionUtils.isEmpty(list)) {
                // 插入数据库的列表
                for (int i=0;i<list.size();i++){
                    saveData(list.get(i));
                }
        }
    }



    /**
     * 存储数据库
     * @param bgcfBatchTemplate
     */
    private void saveData(UserExcel bgcfBatchTemplate) {
        log.info("{}条数据，开始存储数据库！", list.size());
        if (!CollectionUtils.isEmpty(list)) {
            User item = new User();
                BeanUtils.copyProperties(bgcfBatchTemplate, item);
            userMapper.insertUser(item);

        }
        log.info("存储数据库成功！");
    }
}
